package com.artisan.common.utils.wxpay;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.SimpleHttpConnectionManager;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpClientParams;

import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;


public class payWxUtil {
	
	
	public static String URL="https://api.mch.weixin.qq.com/pay/unifiedorder";
    @SuppressWarnings("deprecation")
    public JSONObject getPrepayJson(String xml){
        HttpClient httpClient = new HttpClient(new HttpClientParams(),new SimpleHttpConnectionManager(true) ); 
        InputStream is = null;
        PostMethod method=null;
        try {
             String url =URL;
             method = HttpClientUtils.postMethod(url);
             NameValuePair[] data ={ new NameValuePair("Select1","专利名称"),new NameValuePair("Text1","sh")};
             method.setRequestBody(xml);
             httpClient.executeMethod(method);
            //读取响应
             is = method.getResponseBodyAsStream();
            JSONObject o =Xml2JsonUtil.xml2JSON(is);
            return o;
        } catch (Exception e) {
            e.printStackTrace();
        }finally{
            if(method!=null){
                method.releaseConnection();
            }
            if(is!=null){
                try {
                    is.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
        }
        return null;
    }
    
    public  String getPrepayid(String xml){
        try {
            JSONObject jo=getPrepayJson(xml);
            JSONObject element=jo.getJSONObject("xml");
            String prepayid=((JSONArray)element.get("prepay_id")).get(0).toString();
            return prepayid;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    
    public  String orderNum(){
        String key = formatTime2MMddHHmmss() + "-" + getRandom();
        return key.length() > 15 ? key.substring(0, 15) : key;
    }

    public static String formatTime2MMddHHmmss()
    {
        return new SimpleDateFormat("MMddHHmmss").format(System.currentTimeMillis());
    }


    public static String getRandom()
    {
        return String.valueOf(Math.random() * 9000 + 1000);
    }
}
